<?php

namespace app\util;

use PHPQRCode\Constants;
use PHPQRCode\QRcode;

/*
 * 文件类
 */
class File
{
    public $error = '';

    /*
     * 返回错误信息
     */
    public function getError()
    {
        return $this->error;
    }

    /*
     * 上传图片
     * \think\File $file
     */
    public function uploadImage($file, $folder)
    {
        $uploadInfo = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . $folder);
        if ($uploadInfo) {
            return $folder . $uploadInfo->getSaveName();
        } else {
            return false;
        }
    }

    /*
     * 上传多张图片
     * \think\File[] $files
     */
    public function uploadMutilImage($files, $folder)
    {
        $imgArray = [];

        foreach ($files as $file) {
            $uploadInfo = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . $folder);
            if ($uploadInfo) {
                $img = $folder . $uploadInfo->getSaveName();
                array_push($imgArray, $img);
            }
        }

        return $imgArray;
    }

    /*
     * 删除图片
     * string $file
     */
    public function deleteImage($file)
    {
        $file = ROOT_PATH . 'public' . DS . 'upload' . DS . $file;
        if (is_file($file)) {
            return unlink($file);
        } else {
            return true;
        }
    }

    /*
     * 检查图片
     */
    public function checkImg($file)
    {
        if ($file->checkImg()) {
            if ($file->checkExt(['jpg', 'jpeg', 'png'])) {
                if ($file->checkSize(1048576)) {
                    return true;
                } else {
                    $this->error = '图片不能超过1MB';
                    return false;
                }
            } else {
                $this->error = '图片格式为jpg/jpeg/png';
                return false;
            }
        } else {
            $this->error = '非法图像文件';
            return false;
        }
    }

}